# -*- coding: utf-8 -*-
import frappe

def has_app_permission():
    """检查用户是否有权限访问CAS应用"""
    if frappe.session.user == "Administrator":
        return True
    
    # 检查用户是否有财务角色
    roles = frappe.get_roles()
    if "Accounts Manager" in roles or "Accounts User" in roles or "System Manager" in roles:
        return True
    
    return False

def has_permission(doc, ptype, user):
    """检查用户是否有权限访问API"""
    if frappe.session.user == "Administrator":
        return True
    
    # 检查用户是否有财务角色
    roles = frappe.get_roles(user)
    if "Accounts Manager" in roles or "Accounts User" in roles or "System Manager" in roles:
        return True
    
    return False

def get_permission_query_conditions(user):
    """获取权限查询条件"""
    if not user:
        user = frappe.session.user
    
    if frappe.session.user == "Administrator":
        return ""
    
    # 检查用户是否有财务角色
    roles = frappe.get_roles(user)
    if "Accounts Manager" in roles or "Accounts User" in roles or "System Manager" in roles:
        return ""
    
    # 如果没有财务角色，只返回用户有权限的公司
    user_companies = frappe.get_all("Company", filters={"user": user}, pluck="name")
    if user_companies:
        return f"`tabCompany`.name IN ({', '.join([f'"{c}"' for c in user_companies])})"
    
    return "1=0"  # 无权限